<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span class="title">个人信息</span>
          <el-button type="primary" @click="handleSave" :loading="loading">保存修改</el-button>
        </div>
      </template>

      <el-form :model="userForm" :rules="rules" ref="formRef" label-width="100px" class="profile-form">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="avatar-tip">点击上传头像，建议尺寸 200x200</div>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>

        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="userForm.nickname" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-tag v-for="role in userForm.roles" :key="role.id" class="role-tag">
            {{ role.name }}
          </el-tag>
        </el-form-item>
      </el-form>

      <div class="password-section">
        <div class="divider">
          <el-divider content-position="left">密码修改</el-divider>
        </div>
        <router-link to="/user/change-password" class="change-password-link">
          <el-button type="default">修改密码</el-button>
        </router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getUserInfo, updateUserProfile } from "@/api/user";
import { getToken, setToken } from "@/utils/auth";
import { refresh } from "@/api/auth";
import { uploadFile } from "@/api/common";
import { useUserStore } from "@/stores/user";

// 上传相关配置
const uploadUrl = process.env.VUE_APP_API_URL + "/file/upload";
// token响应式数据
const token = ref(getToken());
const uploadHeaders = computed(() => {
  return token.value ? { Authorization: "Bearer " + token.value } : {};
});

const formRef = ref(null);
const loading = ref(false);

const userStore = useUserStore();

// 表单数据
const userForm = reactive({
  id: "",
  username: "",
  nickname: "",
  avatar: "",
  email: "",
  phone: "",
  gender: 0,
  roles: [],
});

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度应为2-20个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
};

const handleAvatarSuccess = (res) => {
  if (res.success) {
    userForm.avatar = res.data;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(res.message || "头像上传失败");
  }
};

// 图片上传失败的处理
const handleAvatarError = async (error, file) => {
  try {
    const refreshResult = await refresh();
    if (refreshResult.success) {
      //更新token
      setToken(refreshResult.data);
      // 更新响应式 token
      token.value = refreshResult.data;
      // 重新上传
      const data = new FormData();
      data.append("file", file.raw || file);
      const uploadResult = await uploadFile(data);
      if (uploadResult.success) {
        userForm.avatar = uploadResult.data;
      } else {
        ElMessage.error("图片上传失败");
      }
    } else {
      ElMessage.error("图片上传失败");
    }
  } catch (err) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败");
  }
};

const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error("头像只能是JPG或PNG格式!");
    return false;
  }

  if (!isLt2M) {
    ElMessage.error("头像大小不能超过2MB!");
    return false;
  }

  return isJpgOrPng && isLt2M;
};

// 保存个人信息
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    loading.value = true;
    const response = await updateUserProfile({
      id: userForm.id,
      nickName: userForm.nickname,
      email: userForm.email,
      phone: userForm.phone,
      gender: userForm.gender,
      avatar: userForm.avatar,
    });
    if (response.success) {
      ElMessage.success("个人信息修改成功");
      // 更新UserInfo
      const response = await getUserInfo();
      if (response.success && response.data) {
        userStore.setUserInfo(response.data);
      }
    } else {
      ElMessage.error(response.message || "个人信息修改失败");
    }
  } catch (error) {
    console.error("表单验证失败", error);
  } finally {
    loading.value = false;
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo();
    if (response.success && response.data) {
      const userData = response.data;
      Object.assign(userForm, userData);
      if (userData.userRoleList && userData.userRoleList.length > 0) {
        userForm.roles = userData.userRoleList.map((role) => {
          return {
            id: role.roleId,
            name: role.roleName,
          };
        });
        console.log("用户角色列表:", userForm.roles);
      }
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
    ElMessage.error("获取用户信息失败，请刷新重试");
  }
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.profile-form {
  margin-top: 20px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.role-tag {
  margin-right: 8px;
}

.password-section {
  margin-top: 30px;
}

.divider {
  margin-bottom: 20px;
}

.change-password-link {
  text-decoration: none;
}
</style>
